/**
 * @param {*} options 
 */
var DataHandler = function(options){
    var t = this;
    t.options = $.parseJSON(JSON.stringify(options));
    t.$dom = $(options.container);
    t._initdom_();
    t._init_event_();
    t._load_({
    	"userConditions":t.options.userConditions,
    	"size":20,
    	"page":1,
    	"needTotal":true
    });
}
/**
 * 重新加载
 */
DataHandler.prototype.reload = function(userConditions){
	var t = this;
	t.options.userConditions = userConditions
	t._load_({
    	"userConditions":t.options.userConditions,
    	"size":20,
    	"page":1,
    	"needTotal":true
    });
}
/**
 * 加载并渲染数据
 */
DataHandler.prototype._load_=function(params){
	var t = this;
	var options = t.options;
	params.designId = options.designId;
	params.usePage = true;
	cmp.dialog.loading();
	rptApi.getStatsResult({},params,{
		success:function(rs){
			t._datas_ = rs;
			var datas = rs, data = rs.data , displayFields = rs.displayFields , fields = rs.fields ;
			var dataLength = data.length;
			t.resetpostion();
			var oneHeadRow = [] , towHeadRow = [] ;
			for ( var i = 0 , len1 = displayFields.length ; i < len1 ; i ++) {
				var disField = displayFields[i] , key = disField.key;
				var head = {colspan:1,rowspan:1};
				if(key.indexOf('-') < 0){
					head.key = key;
					oneHeadRow.push(head);
				}else{
					var keyArr = key.split('-') , key0 = keyArr[0] , key1 = keyArr[1];
					var lastHead = oneHeadRow.pop();
					if(lastHead.key == key0){
						lastHead.colspan = lastHead.colspan + 1;
						oneHeadRow.push(lastHead);
					}else{
						oneHeadRow.push(lastHead);
						head.key = key0;
						oneHeadRow.push(head);
					}
					//第二行
					var head2 = {colspan:1,rowspan:1};
					head2.key = key1;
					towHeadRow.push(head2);
				}
			}
			if(towHeadRow.length > 0){//有两行表头
				t.$dom.find(".qt-tb-body").css('top','70px');
				for ( var i = 0 , len1 = oneHeadRow.length ; i < len1 ; i ++) {
					if(i == oneHeadRow[i].key){//行表头
						oneHeadRow[i].rowspan = 2;
					}
				}
			}
			
			var  wd = window.innerWidth,dflength = displayFields.length;
			t._cellWidth_ = 110;
			if(dflength * 100 < wd){//当页无法撑开的时候设置固定的百分比
				t._cellWidth_ = Math.floor(wd/dflength);
			}
			//渲染表头
			var header = DataHandler.headTpl.render({
				oneHeadRow:oneHeadRow,
				towHeadRow:towHeadRow,
				fields:fields,
				"cellWidth":t._cellWidth_
			});
			t.$dom.find(".qt-tb-header tbody").html(header);
			
			if(dataLength == 0){
				t.$dom.find(".qt-tb-body tbody").html("");
				t.$dom.find(".qt-tb-footer .pages").html("-/-");
			}else{
				var tbody = DataHandler.tbodyTpl.render({
					displayFields:displayFields,
					data:data,
					fields:fields,
					"cellWidth":t._cellWidth_
				});
				t.$dom.find(".qt-tb-body tbody").html(tbody);
				t.$dom.find(".qt-tb-footer .pages").html(datas.page + "/" + datas.pages + "页");
			}
			cmp.dialog.loading(false);
		},
		error:function(error){
			cmp.dialog.loading(false);
			var cmpHandled = cmp.errorHandler(error);
			if (!cmpHandled) {
				if (error.message) {
					DataHandler.alert(error.message);
				} else {
					DataHandler.alert(cmp.toJSON(error));
				}
			}
		}
	});
}

DataHandler.prototype._initdom_ = function(){
	this.$dom.html(DataHandler.tableTpl);
}
/**
 * 初始化事件
 */
DataHandler.prototype._init_event_ = function(){
	var t = this;
	
	//穿透
	t.$dom.on("click",".qt-tb-body tbody tr .penet-cell",function(){
		var $cell = $(this) , rowNum = $cell.parents("tr").attr("row-num") , colNum = $cell.parent("td").attr("col-num");
		var displayFields = t._datas_.displayFields, rowData = t._datas_.data[rowNum] , disField = displayFields[colNum];
		if(!disField.penetratable){
			return;
		}
		if(t.options.isPreview){
			return;
		}
		cmp.dialog.loading();
		var fields = t._datas_.fields;
		var titleName = '' , values = {} ;
		for ( var i = 0 , len1 = displayFields.length ; i < len1 ; i ++) {
			var dKey = displayFields[i].key ;
			if (dKey.indexOf('-') < 0 && fields[dKey].type == 'H') {
				titleName += (rowData[dKey].v || '') + '_';
				var vKey = fields[dKey].key;
				values[vKey]= rowData[dKey].sv;
			}
		}
		
		var dataKey = disField.key , fieldIndex = (dataKey.indexOf('-') < 0) ? parseInt(dataKey) : parseInt(dataKey.split('-')[1]);
		// 交叉列
		if (dataKey.indexOf('-') >= 0) {
			var crossIndex = dataKey.split('-')[0];
			titleName += fields[crossIndex].display + '_';
			var vKey = fields[crossIndex].key;
			values[vKey]= fields[crossIndex].value;
		}
		var showField = fields[fieldIndex];
		titleName += showField.display;
		titleName += '(';
		if (showField.calcType == 'count') {
			titleName += cmp.i18n("report.result.common.count");//cmp.i18n("report.common.nodata")
		} else if (showField.calcType == 'sum') {
			titleName += cmp.i18n("report.result.common.sum");
		} else if (showField.calcType == 'avg') {
			titleName += cmp.i18n("report.result.common.avg");
		} else if (showField.calcType == 'max') {
			titleName += cmp.i18n("report.result.common.max");
		} else if (showField.calcType == 'min') {
			titleName += cmp.i18n("report.result.common.min");
		} else if (showField.calcType == 'earliest') {
			titleName += cmp.i18n("report.result.common.earliest");
		} else if (showField.calcType == 'latest') {
			titleName += cmp.i18n("report.result.common.latest");
		}
		titleName += ')';
		var titleValue = rowData[dataKey].v;
		titleValue = (null == titleValue) ? 0 : titleValue;
		
		rptApi.getStatsPenetrateInfo({},{designId:t.options.designId},{
			success:function(rs){
				if(rs.penetrateMode == 'query'){
					RptUtils.load_jscss([vreportPath + "/vreport_m_api.s3js"],[],function(){
						var toDesignId = rs.designId ,headFieldMaps = rs.headFieldMaps , filterFieldMaps = rs.filterFieldMaps;
						var filterValue = RptUtils.getFilterValue(values,t.options.userConditions,headFieldMaps,filterFieldMaps);
						vreportApi.reportView({rptInfo:{module:'4',relatedId:toDesignId,filterValue:filterValue}});
					});
				}else{
					var params = {titleName:titleName,titleValue:titleValue,
							designId:t.options.designId,
							statsField:fields[fieldIndex].key,
							"userConditions":t.options.userConditions,
							fieldValues:values
					};
					cmp.href.next(vreportPath + "/html/defaultPenetList.html",params);
				}
				cmp.dialog.loading(false);
			},
			error:function(error){
				cmp.dialog.loading(false);
				var cmpHandled = cmp.errorHandler(error);
				if (!cmpHandled) {
					if (error.message) {
						DataHandler.alert(error.message);
					} else {
						DataHandler.alert(cmp.toJSON(error));
					}
				}
			}
		});
	}).on("click",".prePage",function(){//上一页
		var page = parseInt(t._datas_.page) - 1;
		if(page > 0){
			t._load_({
				"userConditions":t.options.userConditions,
				"size":20,
				"page":page,
				"needTotal":true
			});
		}
	}).on("click",".nextPage",function(){//下一页
		var page = parseInt(t._datas_.page) + 1;
		if(page <= t._datas_.pages){
			t._load_({
				"userConditions":t.options.userConditions,
				"size":20,
				"page":page,
				"needTotal":true
			});
		}
	}).on("click",".pages",function(){//分页
	});

	t.totalX =0 ;
	t.totalY=0;
	var timer = null;
	var limitWidth = 0 , limitHeight = 0;
	var cw = $(window).width();
	t.$dom.on("touchstart",function(e){
		var start = e.changedTouches[0];
		startX = start.pageX;
		startY = start.pageY;
		limitWidth = cw - t.$dom.find(".qt-tb-header-table").width();
		limitHeight = t.$dom.find(".qt-tb-body").height() - t.$dom.find(".qt-tb-body-table").height();
	}).on("touchmove",function(e){
		if(timer !== null){
			clearTimeout(timer);
		}
		var move = e.changedTouches[0];
		timer = setTimeout(function(){
			var moveX = move.pageX;
			var moveY = move.pageY;
			var thisEndX = t.totalX - (startX - moveX);
			var thisEndY = t.totalY - (startY - moveY);
			if(thisEndX > 0){
				thisEndX =0;
			}else if(thisEndX < limitWidth){
				thisEndX = limitWidth;
			}
			if(thisEndY > 0  || limitHeight > 0){
				thisEndY =0;
			}else if(thisEndY < limitHeight ){
				thisEndY = limitHeight;
			}
			t.$dom.find(".qt-tb-header-table").css("transform","translateX(" + thisEndX + "px)");//x y
			t.$dom.find(".qt-tb-body-table").css("transform","translate(" + thisEndX + "px," +  thisEndY + "px)");//x y
		},10);//延期10ms 避免卡卡卡
	}).on("touchend",function(e){
		var move = e.changedTouches[0];
		var moveX = move.pageX;
		var moveY = move.pageY;
		t.totalX = t.totalX - (startX - moveX);
		t.totalY = t.totalY - (startY - moveY);
		if(t.totalX > 0){
			t.totalX = 0;
		}else if(t.totalX < limitWidth){
			t.totalX = limitWidth;
		}
		if(t.totalY > 0 || limitHeight > 0){
			t.totalY = 0;
		}else if(t.totalY < limitHeight){
			t.totalY = limitHeight;
		}
		t.$dom.find(".qt-tb-header-table").css("transform","translateX(" + t.totalX + "px)");//x y
		t.$dom.find(".qt-tb-body-table").css("transform","translate(" + t.totalX + "px," +  t.totalY + "px)");//x y
		if(timer !== null){
			clearTimeout(timer);
		}
	});
	
}

DataHandler.prototype.resetpostion=function(penetrateInfo,designId){
	this.totalX =0 ;
	this.totalY=0;
	this.$dom.find(".qt-tb-header-table").css("transform","translateX(0px)");//x y
	this.$dom.find(".qt-tb-body-table").css("transform","translate(0px,0px)");//x y
}

DataHandler.alert = function(tips){
	cmp.notification.alert(tips);
}
DataHandler.toHtml = function(a) {
	try {
		return a ? (a = a.replace(/&/g, "&amp;"),
		a = a.replace(/</g, "&lt;"),
		a = a.replace(/>/g, "&gt;"),
		a = a.replace(/\'/g, "&#039;"),
		a = a.replace(/"/g, "&#034;"),
		a = a.replace(/ /g, "&nbsp;"),
		a) : ""
	} catch (error) {
		console.log("toHtml",a);
		return "";
	}
}
DataHandler.headTpl = laytpl('\
		<tr >\
		{{#\
			for(var i=0;i<d.oneHeadRow.length;i++){\
				var head = d.oneHeadRow[i], key = head.key ;\
		}}\
			<td colspan="{{head.colspan }}" rowspan="{{head.rowspan }}"><div class="qt-tb-cell cell-rowspan-{{head.rowspan }}" style="width:{{d.cellWidth * head.colspan }}px">{{=d.fields[key].display }}</div></td>\
		{{#\
			}\
		}}\
		</tr>\
		{{# if(d.towHeadRow.length > 0){ }}\
			<tr >\
			{{#\
				for(var i=0;i<d.towHeadRow.length;i++){\
					var head = d.towHeadRow[i], key = head.key ;\
			}}\
				<td colspan="{{head.colspan }}" rowspan="{{head.rowspan }}"><div class="qt-tb-cell" style="width:{{d.cellWidth }}px">{{=d.fields[key].display }}</div></td>\
			{{#\
				}\
			}}\
		{{# } }}\
');
DataHandler.tbodyTpl = laytpl('\
	{{#\
		var fields = d.fields, displayFields = d.displayFields ;\
		for ( var i = 0 , len1 = d.data.length ; i < len1 ; i ++) {\
			var rowData = d.data[i];\
	}}\
		<tr row-num="{{i}}">\
			{{#\
			for ( var j = 0 , len2 = displayFields.length ; j < len2 ; j ++) {\
					var penetratable = displayFields[j].penetratable , key = displayFields[j].key ;\
			}}\
				<td col-num="{{j}}"><div class="qt-tb-cell {{# if(penetratable){ }}penet-cell{{# } }}" style="width:{{d.cellWidth }}px;{{=rowData[key].css}}">{{=rowData[key].v }}</div></td>\
			{{#\
				}\
			}}\
		</tr>\
	{{#\
		}\
	}}\
');

DataHandler.tableTpl = '\
<div class=qt-tb-ct>\
	<div class="qt-tb-header">\
		<table class="qt-tb-header-table">\
			<tbody></tbody>\
		</table>\
	</div>\
	<div class="qt-tb-body">\
		<table class="qt-tb-body-table">\
			<tbody></tbody>\
		</table>\
	</div>\
</div>\
<div class="qt-tb-footer">\
	<span class="cmp-icon cmp-icon-back prePage"></span>\
	<span class="pages">5/100</span>\
	<span class="cmp-icon cmp-icon-forward nextPage"></span>\
</div>';